<?php

namespace App\Http\Requests\Admin;

use App\Models\Category;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CategoryRequest extends FormRequest
{
	/**
	 * Determine if the user is authorized to make this request.
	 *
	 * @return bool
	 */
	public function authorize()
	{
		return true;
	}

	/**
	 * Get the validation rules that apply to the request.
	 *
	 * @return array
	 */
	public function rules()
	{
		return [
			'pid'=> [
				'required',
				'integer',
				'max:1000',
				function ($attribute, $value, $fail){
					if ((int)$value != '0') {
						$checkExist = Category::find($value);
						if ( ! $checkExist) {
							return $fail('父类不存在');
						}
					}
				},
			],
			'category_name' => [
				'required',
				'regex:/^[\x{4e00}-\x{9fa5}A-Za-z0-9-_]+$/u'
			]
		];
	}


	public function messages()
	{
		return [
			'category_name.regex' => '分类名只能是中文，数字，英文，下划线组成',
			'pid.exists'          => '父级分类不存在',
		];
	}
}
